package battleships;

import java.util.HashMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

public class User {
	private Integer userId;
	private Integer played, won;
	private String name;
	private HashMap<String, String> status;
	public BlockingQueue<String> message;

	public User(Integer userId) {
		super();
		this.userId = userId;
		status = new HashMap<String, String>();
		status.put("available", "true");
		message = new ArrayBlockingQueue<String>(10);
		name = "undefined"+userId;
		played = won = 0;
		
		Chat.messages.put(userId, new ArrayBlockingQueue<String>(100));
		Chat.userlist.put(userId, new ArrayBlockingQueue<Boolean>(5));
	}

	public Integer getUserId() {
		return userId;
	}
	
	public Integer getWins() {
		return won;
	}
	public Integer getTotal() {
		return played;
	}
	public void addGameEnd(boolean won) {
		if (won) this.won++;
		played++;
	}
	
	public void setName(String newName) {
		name = newName;
	}
	
	public String getName() {
		return name;
	}
	
	public void putMessage(String msg) {
		try {message.put(msg);} catch (InterruptedException e) { throw new RuntimeException(e); }
	}
	
	public String getMessage(int timeout) {
		try {
			String msg = message.poll(timeout, TimeUnit.SECONDS);
			//System.err.println(userId + " waits for message, got "+ msg);
			return msg == null ? "" : msg;
		} catch (InterruptedException e) { 
			throw new RuntimeException(e); 
		}
	}
	
	public String getMessage() {
		try {
			return message.take();
		} catch (InterruptedException e) { 
			throw new RuntimeException(e); 
		}		
	}
	
	public void setChallenge(Integer challenge) {
		System.err.println(userId + " was challenged by "+challenge);
		if (challenge != null) {
			//putMessage("challenge");
			status.put("challenge", challenge.toString());
		}
		//removing a challenge
		else 
			status.remove("challenge");
	}
	
	public void setChallenging(Integer challenge) {
		if (challenge != null)
			status.put("challenging", challenge.toString());
		else 
			status.remove("challenging");
			
	}	
	
	public Integer getChallenger() {
		if (status.containsKey("challenge"))
			return Integer.parseInt(status.get("challenge"));
		return null;
	}
	public Integer getChallenging() {
		if (status.containsKey("challenging"))
			return Integer.parseInt(status.get("challenging"));
		return null;
	}
	
	public boolean isAvailable() {
		return status.get("available") == "true";
	}
	
	public void clearMessages() {
		while (message.poll() != null);
	}
	
	public void setAvailable(boolean val) {
		status.put("available", val ? "true" : "false");
		
	}
}
